package com.atguigu.tingshu.user.service.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.user.factory.StrategyFactory;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    @Autowired
    private StrategyFactory strategyFactory;

    @Override
    public void updateVipExpireStatus() {
        //  操作user_info 表;
        //  update user_info set is_vip = 0 where is_vip = 1 and vip_expire_time < now()
        userInfoMapper.updateIsVip();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        try {
            //  使用工厂调用策略模式
            ItemTypeStrategy typeStrategy = strategyFactory.getStrategy(userPaidRecordVo.getItemType());
            //  直接调用保存信息方法
            typeStrategy.savePaidRecord(userPaidRecordVo);
            //  记录用户购买信息 ： 专辑：声音：vip
            //            if (userPaidRecordVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_ALBUM)) {
            //                //  专辑 user_paid_album
            //                UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getUserId, userPaidRecordVo.getUserId()).eq(UserPaidAlbum::getAlbumId, userPaidRecordVo.getItemIdList().get(0)));
            //                if (null != userPaidAlbum) {
            //                    return;
            //                }
            //                //  创建对象
            //                userPaidAlbum = new UserPaidAlbum();
            //                userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));
            //                userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
            //                userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
            //                //  保存数据
            //                userPaidAlbumMapper.insert(userPaidAlbum);
            //            } else if (userPaidRecordVo.getItemType().equals(SystemConstant.ORDER_ITEM_TYPE_TRACK)) {
            //                //  声音 user_paid_track
            //                Long count = userPaidTrackMapper.selectCount(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userPaidRecordVo.getUserId()).eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo()));
            //                if (count > 0) {
            //                    return;
            //                }
            //                //  创建对象并保存数据
            //                List<Long> itemIdList = userPaidRecordVo.getItemIdList();
            //                //  需要根据声音Id获取到声音对象;
            //                Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(itemIdList.get(0));
            //                Assert.notNull(trackInfoResult, "trackInfoResult不能为空");
            //                TrackInfo trackInfo = trackInfoResult.getData();
            //                Assert.notNull(trackInfo, "trackInfo不能为空");
            //                if (!CollectionUtils.isEmpty(itemIdList)) {
            //                    for (Long trackId : itemIdList) {
            //                        UserPaidTrack userPaidTrack = new UserPaidTrack();
            //                        //  赋值：
            //                        userPaidTrack.setTrackId(trackId);
            //                        userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            //                        userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            //                        //  获取专辑对象：才能赋值专辑Id;
            //                        userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            //                        userPaidTrackMapper.insert(userPaidTrack);
            //                    }
            //                }
            //            } else {
            //                //  vip user_vip_service
            //                //  需要获取用户的身份信息！
            //                UserInfo userInfo = this.getById(userPaidRecordVo.getUserId());
            //                //  还需要获取到用户购买有效期！
            //                Long serviceId = userPaidRecordVo.getItemIdList().get(0);
            //                VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(serviceId);
            //                //  创建对象：
            //                UserVipService userVipService = new UserVipService();
            //                userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
            //                userVipService.setUserId(userPaidRecordVo.getUserId());
            //                userVipService.setStartTime(new Date());
            //                //  创建对象
            //                LocalDateTime localDateTime = new LocalDateTime(new Date());
            //                //  判断续期情况：当前用户属于VIP 并且 过期时间在系统时间之后！
            //                if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(new Date())) {
            //                    //  在过期时间基础上+购买时间;
            //                    Date vipExpireTime = userInfo.getVipExpireTime();
            //                    //  创建localDateTime
            //                    localDateTime = new LocalDateTime(vipExpireTime);
            //                }
            //                //  获取过期时间
            //                Date vipExpireTime = localDateTime.plusMonths(vipServiceConfig.getServiceMonth()).toDate();
            //                //  设置过期时间
            //                userVipService.setExpireTime(vipExpireTime);
            //                //  保存数据
            //                userVipServiceMapper.insert(userVipService);
            //
            //                //  int i = 1/0;
            //                //  修改用户的vip状态
            //                userInfo.setIsVip(1);
            //                userInfo.setVipExpireTime(vipExpireTime);
            //                //  更新数据:
            //                this.updateById(userInfo);
            //            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            //  抛出异常。
            throw new GuiguException(ResultCodeEnum.SERVICE_ERROR);
        }
    }

    @Override
    public List<Long> findUserPaidTrackList(Long albumId, Long userId) {
        //  select * from user_paid_track where user_id = 26 and album_id = 1429;
        return userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getAlbumId, albumId).eq(UserPaidTrack::getUserId, userId)).stream().map(userPaidTrack -> userPaidTrack.getTrackId()).collect(Collectors.toList());
    }

    @Override
    public Boolean isPaidAlbum(Long albumId, Long userId) {
        //	select * from user_paid_album where album_id = ? and user_id = ?;
        return userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, albumId).eq(UserPaidAlbum::getUserId, userId)) != null;
    }

    @Override
    public Map<Long, Integer> userIsPaidTrack(Long albumId, List<Long> trackIdList, Long userId) {
        //	表结构要了解; user_paid_album
        // 	select * from user_paid_album where album_id = ? and user_id = ?
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, albumId).eq(UserPaidAlbum::getUserId, userId));
        //	判断
        if (null != userPaidAlbum) {
            //	购买过这个专辑.
            Map<Long, Integer> map = trackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 1));
            //	返回数据
            return map;
        } else {
            //	用户没有购买过专辑，判断用户是否购买过声音Id user_paid_track
            //	select * from user_paid_track where user_id = ? and track_id in (?,?,?);
            LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserPaidTrack::getUserId, userId).in(UserPaidTrack::getTrackId, trackIdList);
            List<Long> trackIdPaidList = userPaidTrackMapper.selectList(wrapper).stream().map(userPaidTrack -> userPaidTrack.getTrackId()).collect(Collectors.toList());
            //	创建一个map 集合
            Map<Long, Integer> map = new HashMap<>();
            //	循环遍历.
            trackIdList.stream().forEach(trackId -> {
                //	判断用户是否购买过声音Id
                if (trackIdPaidList.contains(trackId)) {
                    //	购买过声音
                    map.put(trackId, 1);
                } else {
                    //	没有购买声音
                    map.put(trackId, 0);
                }
            });
            return map;
        }
    }

    @Override
    // @GuiGuCache(prefix = "userInfo:")
    public UserInfoVo getUserInfoVo(Long userId) {
        //  获取缓存中用户数据
        UserInfo userInfo = this.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        //	属性拷贝：
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }
}
